(function() {
 	var global = ( function(){ return this; } )();
 	global.fffCommerce = global.fffCommerce || {};
	global.fffCommerce.events = global.fffCommerce.events||{};
	global.fffCommerce.events.SHOW_LIST=global.fffCommerce.events.SHOW_LIST||'3fCommerce_ShowList';
	                                                                       
 	fffCommerce.ListRenderer = function(){
 	 	var _list;
		var _container;
		this.Attach=function(container) {
			_container=$(container);
			_container.Renderer=this;
			$('body').bind(global.fffCommerce.events.SHOW_LIST,function(ev,list) {
				render(list);
			});
		}
 	 	var render = function(list){
			_container.empty();
			if (!list) throw "Empty data!";
			if (!list.length) throw "The data must be a list";
			$.each(list,function() { if (!isProduct(this)) throw "Elements in the list must be products!"; });
			_list=list;
			$.each(_list, function(){_container.append(getRenderItem(this))});
		};
		var getRenderItem = function (product){
			var item = $('<div class="productItem"></div>');
			var thumb = $('<img class="thumb" />');
			var title = $('<div class="title"></div>');
			var price = $('<div class="price"></div>');
			title.html(product.shortName);
			price.html(formatPrice(product.price));
			thumb.attr("src",product.thumbnail);
			item.append(thumb);
			item.append(title);
			item.append(price);

			item.mouseover(function() { item.addClass('hover'); });
			item.mouseout(function() { item.removeClass('hover'); });
			item.click(function() { 
				item.parent().find('.productItem').removeClass('selected');
				item.addClass('selected');
				$('body').trigger(global.fffCommerce.events.SHOW_DETAILS,product.uid);
			});

			return item;
		};
		var formatPrice = function(price) {
			return '&euro; '+Number(price).toFixed(2);
		};
		var isProduct = function(product) {
			if (!product) return false;
			if (!('shortName' in product)) return false;
			if (!('price' in product)) return false;
			if (!('thumbnail' in product)) return false;
			return true;
		}
	};
})();


$(function(){
	var renderer=new fffCommerce.ListRenderer();
	renderer.Attach('#list');
//	$('body').trigger(fffCommerce.events.SHOW_LIST,[list]);
});